#pragma once

#include <string>
#include <cerrno>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>      // 用于设置非阻塞
#include <sys/select.h> // 用于 select


namespace GiSo {


class TcpClient {
public:
    TcpClient() : m_Sockfd(-1) {
        // 在构造函数中不创建 socket，延迟到 ConnectToServer
    }

    ~TcpClient() {
        CloseSocket();
    }

    // 禁止拷贝
    TcpClient(const TcpClient&) = delete;
    TcpClient& operator=(const TcpClient&) = delete;

    // 移动语义
    TcpClient(TcpClient&& other) noexcept : m_Sockfd(other.m_Sockfd) {
        other.m_Sockfd = -1;
    }
    TcpClient& operator=(TcpClient&& other) noexcept {
        if (this != &other) {
            CloseSocket();
            m_Sockfd = other.m_Sockfd;
            other.m_Sockfd = -1;
        }
        return *this;
    }

    bool ConnectToServer(const std::string& ip, uint16_t port);
    bool Wait(int timeoutMs = 1000);
    ssize_t SendData(const std::string& data);
    std::string ReceiveData(size_t maxBytes = 1024);
    void Disconnect();
    bool IsConnected() const {
        return m_Sockfd != -1;
    }

private:
    void CloseSocket();

    int m_Sockfd;
};

}